//支付失败
var server = require('../../utils/server');
var common = require('../../utils/common');
const app = getApp();
Page({
  data: {
    recommendGoods: [],
    errmesg: "某种原因",
    isPayWx: false
  },
  onLoad: function(options) {
    this.setData({
      errmesg: options.errmesg,
      payway: options.way
    })
  },
  onShow: function() {
    wx.getStorage({
      key: 'storeId',
      success: res => {
        this.data.storeId = res.data;
        this.getRecommendGoods();
      },
    })
  },
  getRecommendGoods() {
    wx.getStorage({
      key: 'recommendIds',
      success: resp => {
        server.postJSON(common.storePath + 'store/getrecommendgoods/', {
          "store_id": this.data.storeId,
          "recommend_type": 'like',
          "recommend_num": 4,
          "goods_ids": resp.data
        }, res => {
          if (res.data.errno == '0') {
            if (res.data.data.length > 0) {
              (res.data.data).forEach((item, index) => {
                item.isCanAdd = true;
                item.isCanReduce = true;
              })
              this.setData({
                recommendGoods: res.data.data
              })
              if (common.compareVersion(wx.getSystemInfoSync().SDKVersion, '1.9.6') >= 0) {
                this.data.recommendGoods.forEach((item, idx) => {
                  let intersect = wx.createIntersectionObserver();
                  intersect.relativeToViewport().observe('#easy-rec-' + item.goods_id, (res) => {
                    intersect.disconnect(); //使用disconnect，使得目标节点只曝光一次
                    console.log('曝光#easy-rec-' + item.goods_id);
                    server.postJSON(common.storePath + 'store/reportusertrace/', {
                      "store_id": this.data.storeId,
                      "recommend_type": '猜你喜欢',
                      "list": [{
                        "goods_id": item.goods_id,
                        "trace_id": item.trace_id,
                        "position": idx
                      }]
                    }, res => {
                      if (res.data.errno == '0') {
                        console.log('曝光成功')
                      } else {
                        common.showErrorToast(res.data.errmsg)
                      }
                    })
                  })
                })
              }
            }
          } else {
            common.showErrorToast(res.data.errmsg)
          }
        })
      },
    })

  },
  //添加为你推荐商品
  addRecommendCart(e) {
    var index = e.currentTarget.dataset.index;
    this.setData({
      ['recommendGoods[' + index + '].isCanAdd']: false
    })
    server.postJSON(common.storePath + 'cart/addgoods/', {
      "store_id": this.data.storeId,
      "goods_id": e.currentTarget.dataset.id,
      "trace_id": e.currentTarget.dataset.traceid
    }, res => {
      if (res.data.errno == "0") {
        common.showErrorToast("添加成功");
        this.setData({
          cartNum: parseInt(this.data.cartNum) + 1,
          ['recommendGoods[' + index + '].isCanAdd']: true,
          ['recommendGoods[' + index + '].cart_num']: parseInt(this.data.recommendGoods[index].cart_num) + 1
        })
      } else {
        this.setData({
          ['recommendGoods[' + index + '].isCanAdd']: true
        })
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  addEmpty() {
    console.log('waiting add success')
  },
  goToPay() {
    // if (this.data.payway == '0') {
    this.setData({
      isPayWx: true
    })
    wx.getStorage({
      key: 'orderId',
      success: response => {
        var orderid = response.data;
        this.data.orderid = response.data;
        app.globalData.isBindYcCard = false;
        var param = {
          "currency": '63',
          "order_id": orderid
        }
        common.pay(param).then(res => {
          if (res.errno == "0") {
            var outtradeno = res.data.out_trade_no;
            //发起支付
            var payParam = res.data;
            var that = this;
            payParam.complete = function(ret3) {
              common.showLoading("支付中...");
              //支付成功
              var isSuc = ret3.errMsg == 'requestPayment:ok';
              console.log(isSuc)
              wx.reportAnalytics('pay_status', {
                paystatus: isSuc,
                orderid: orderid
              });
              if (isSuc) {
                wx.reportAnalytics('pay_success', {
                  paystatus: isSuc,
                  orderid: orderid
                });
                server.postJSON(common.storePath + 'order/payrespond/', {
                  'out_trade_no': outtradeno
                }, resp => {
                  that.setData({
                    isPayWx: true
                  })
                  wx.removeStorage({
                    key: 'channelid',
                    success: function(res) {
                      console.log('clearcid')
                    },
                  })
                  wx.redirectTo({
                    url: 'paySuccess?orderId=' + orderid
                  })
                })
              } else {
                that.setData({
                  isPayWx: true
                })
                wx.reportAnalytics('pay_fail', {
                  paystatus: isSuc,
                  orderid: orderid
                });
                wx.showToast({
                  title: '支付失败',
                  duration: 2000,
                  complete: function() {
                    wx.redirectTo({
                      url: 'payFail?way=0&&orderId=' + orderid + '&&errmesg=微信支付失败'
                    })
                  }
                });
              }
            }
            wx.requestPayment(payParam);
          } else {
            if (res.errmsg == undefined) {
              common.showToast("数据出错啦T_T，请稍候再试 [-3]");
              time = setTimeout(function() {
                wx.hideToast()
              }, 3500)
            } else if (res.errno == "1000000") {
              this.setData({
                showStorePop: true,
                storeStatusInfo: res.data.status_tip
              })
            } else {
              common.showToast(res.errmsg);
            }
          }
        })
      },
    })
  },
  goToIndex() {
    wx.getStorage({
      key: 'orderId',
      success: res => {
        wx.reLaunch({
          url: '/order/pages/orderDetail?orderId=' + res.data
        })
      },
    })
  }
})